package net.bcxuexi.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;



import net.bcxuexi.tools.MyLog;

public class Gloab {
	/**
	 * 保存全局属性值
	 */
	private static Map<String, String> map = new HashMap<String, String>();

	private final static String resourcesPath = "config.properties";
	private static Gloab gloab;
	private String clientKey = "";
	private String serverIp;
	private int serverPort;
	public String logFile = "client.log";
	private String classesPath = Gloab.class.getClassLoader().getResource("")
			.getPath();

	private Gloab() {

	}

	private void init() {
		Properties prop = loadProperties();
		Set<Object> keys = prop.keySet();
		for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
			String key = (String) iterator.next();
			String value = prop.getProperty(key);
			map.put(key, value);
			if (key.equals("server_ip")) {
				serverIp = value;
				continue;
			} else if (key.equals("server_port")) {
				serverPort = Integer.valueOf(value);
				continue;
			} else if (key.equals("client_key")) {
				clientKey = value;
				continue;
			} else if (key.equals("logFile")) {
				logFile = value;
				continue;
			}
		}
	}
	/**
	 * 获取配置
	 */
	public String getConfig(String key) {
		String value = map.get(key);
		return value;
	}
	public static synchronized Gloab getInstance() {
		if (gloab == null) {
			gloab = new Gloab();
			gloab.init();
		}
		return gloab;
	}

	private Properties loadProperties() {
		Properties props = new Properties();
		InputStream is = null;
		try {
			is = new FileInputStream(new File(classesPath + resourcesPath));
			props.load(is);
		} catch (IOException ex) {
			MyLog.info("Could not load properties from path:" + resourcesPath
					+ ", " + ex.getMessage());
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return props;
	}

	public String getClientKey() {
		return clientKey;
	}

	public String getServerIp() {
		return serverIp;
	}

	public int getServerPort() {
		return serverPort;
	}

	public String getLogFile() {
		return logFile;
	}

	public static void main(String[] args) {
		Gloab.getInstance();
	}
}
